package com.matrix.draft.sockettest.day7;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class HeartBeatServer {

    private String HOST = "127.0.0.1";
    private Integer PORT = 8080;

    public void run(){
        EventLoopGroup masterGroup = new NioEventLoopGroup(1);
        EventLoopGroup slaverGroup = new NioEventLoopGroup();
        try {
            new ServerBootstrap().group(masterGroup,slaverGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            /**
                             * IdleStateHandler是netty提供的空闲状态处理器
                             * long readerIdleTime: 多久无读发送心跳检测包检测是否连接
                             * long writerIdleTime: 多久无写发送心跳检测包检测是否连接
                             * long allIdleTime: 多久无读写发送心跳检测包检测是否连接
                             * TimeUnit unit: 时间单位
                             * Official Explanation: IdleStateHandler triggers an IdleStateEvent when a Channel has not performed read, write, or both for a while.
                             * 官方解释: IdleStateHandler 会在一个Channel一定时间内没有读或写事件时触发IdleStateEvent事件.
                             * 其会通知下一个handler的userEventTriggered方法
                             */
                            ch.pipeline().addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new HeartBeatHandler());
                        }
                    })
                    .bind(HOST,PORT).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            slaverGroup.shutdownGracefully();
            masterGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new HeartBeatServer().run();
    }
}
